<template>
    <div class="item-detail">
        <modal :loading="loading" :show.sync="showModal" @submit="submit" :height="height" :action="action">
            <template slot="header">
                <span>{{title}}</span>

                <span class="m-l-10" v-if="arrow">
                    <button class="btn btn-info btn-xs btn-circle" :disabled="!arrowCanPrevious" @click="$emit('arrow', 'previous')">
                        <i class="fif fif-cc-arrow-left"></i>
                    </button>
                    <button class="btn btn-info btn-xs btn-circle"  :disabled="!arrowCanNext" @click="$emit('arrow', 'next')">
                        <i class="fif fif-cc-arrow-right"></i>
                    </button>
                </span>

            </template>
            <template slot="body">
                <ItemForm
                        v-if="showModal"
                        :value="value"
                        :action="action"
                        @myselect-item="onVSelectInput"
                        @get-file="getFile"
                        @get-clean-fee="getFixedCleanFee"
                ></ItemForm>
            </template>
        </modal>
    </div>
</template>

<script>
    import modal from '@/components/widgets/Modal.vue'
    import ItemForm from '@/components/widgets/ItemForm.vue'
    //import moment from 'moment'
    import {getModel} from '@/api/model'
    import {getRoomStandardCleanFee} from "@/api/order"

    export default {
        name: "ItemDetail",
        components: {modal, ItemForm},
        props: ['show', 'title', 'value', 'id', 'action', 'height', 'loading', 'arrow', 'arrowCanPrevious', 'arrowCanNext', 'noSubmitRefresh'],
        created() {
            this.showModal = this.show
            this.doms = {}
        },
        data() {
            return {
                showModal: false
            }
        },
        watch: {
            show() {
                this.showModal = this.show
            },
            showModal(newVal) {
                this.$emit('update:show', newVal)
            }
        },
        methods: {
            toggleCleanTime(id) {
                this.doms = this.$refs
                let dom = this.$refs[`editTime${id}`][0]
                if (!dom.isOpen) {
                    dom.show()
                } else {
                    dom.hide()
                }
            },
            onVSelectInput(selected) {
                if (['delivery_physical_room__id'].indexOf(selected.key) !== -1) {
                    this._setPhysical(selected.value)
                }
            },
            _setPhysical(id) {
                getModel("Physicalroom", null, {id}).then(res => {
                    for (let i = 0; i < this.value.length; i++) {
                        if (this.value[i].key === 'delivery_address') {
                            this.value[i].value = res.data.list[0].location
                        }
                    }
                })
            },
            getFixedCleanFee(item) {
                let logical_room_id = ''
                let currency = 'JPY'
                this.value.forEach(item => {
                    if (item.key == 'logical_room_id_hook') {
                        logical_room_id = item.value
                    } else if (item.key == 'currency') {
                        currency = item.value
                    }
                })
                if ($.trim(logical_room_id)) {
                    getRoomStandardCleanFee({lid: logical_room_id, currency}).then(res => {
                        if (!res.data.fee) {
                            return $.toast({
                                heading: "This room hasn't fixed clean fee",
                                text: '',
                                position: 'top-right',
                                loaderBg: '#ff6849',
                                icon: 'error',
                            });

                        }

                        item.value = res.data.fee.toFixed(2)
                    })
                } else {
                    $.toast({
                        heading: 'logical_room_id not exist',
                        text: '',
                        position: 'top-right',
                        loaderBg: '#ff6849',
                        icon: 'error',
                    });
                }
            },
            getFile(file) {
                this.file = file
                item.value = file
            },
            submit() {
                for (let i = 0; this.value && i < this.value.length; i++) {
                    let value = this.value[i].value && typeof this.value[i].value == 'object' ? this.value[i].value.value : this.value[i].value
                    if (this.value[i].required && String(value).trim().length === 0 && this.value[i].name !== 'password') {
                        return $.toast({
                            heading: 'Wrong',
                            text: 'You must fill ' + this.value[i].label,
                            position: 'top-right',
                            loaderBg: '#ff6849',
                            icon: 'error'
                        });
                    }
                }
                let v = []
                let res = []
                if (this.value) {
                    $.extend(true, v, this.value)
                }
                let currency = []
                for (let i = 0; i < v.length; i++) {

                    v[i].key = v[i].updateKey ? v[i].updateKey : v[i].key

                    if (v[i] && v[i].inputType === 'select' && v[i].multiple) {
                        v[i].value = v[i].value instanceof Array ? v[i].value.join(';') : v[i].value
                    }

                    v[i].value = !v[i].value && v[i].hasOwnProperty('defaultValue') ? v[i].defaultValue : v[i].value

                    // 货币单位和金钱输入框
                    if (v[i] && v[i].inputType === 'money') {
                        currency.push({
                            key: v[i].currencyKey,
                            value: v[i].currencyVal
                        })
                    }

                    // datetime输入框
                    if (v[i] && v[i].inputType === 'datetimepicker' && v[i].value) {
                        v[i].value = moment(v[i].value).utc().format('YYYY-MM-DD HH:mm:ss')
                    }

                    if (v[i] && v[i].inputType === 'box') {
                        if (v[i].selectedVal !== 'other') {
                            v[i].value = v[i].selectedVal + ':' + v[i].value
                        }
                    }

                    // 用户名输入框，不输入为当前用户名
                    if (v[i] && v[i].inputType === 'user') {
                        v[i].value = v[i].value.length ? v[i].value : this.$store.state.user
                    }

                    // 上传文件输入框
                    if (v[i] && v[i].inputType === 'upload') {
                        v[i].value = undefined
                        if (this.file) {
                            this.$emit('upload', v[1].value, this.file)
                            $("#file").val('')
                        }
                    }

                    // 与正常的checkbox输入内容相反
                    if (v[i].inputType === 'reversecheckbox') {
                        v[i].value = !v[i].value
                    }

                    // datetime表示前端是date输入框，后端是datetime类型
                    if (v[i].inputType === 'datetime') {
                        v[i].value = v[i].value + ' 12:00:00'
                    }

                    // 类型为weekdayTimePicker的字段为辅助字段
                    if (v[i] && v[i].inputType === 'weekdayTimePicker') continue;


                    // 类型为date，不输入则发送该字段给后端
                    if (v[i] && !v[i].value  &&  v[i].inputType === 'date') continue;

                    res.push(v[i])
                }

                if (currency.length) {
                    res = res.concat(currency)
                }

                this.$emit('submit', this.action, res, this.noSubmitRefresh)
            }
        },
        mounted() {
            $(".item-detail").slimScroll({height: "100%", position: "left", size: "6px", color: "rgba(0,0,0,0.5)"})
        }
    }
</script>

<style lang="stylus">
    .item-detail
        position: relative;
        .checkbox label::after
            padding-top: 7px
        .vdatetime-input
            width: 100%;
            background-color: #fff;
            border: 1px solid #e4e7ea;
            border-radius: 4px;
            -webkit-box-shadow: none;
            box-shadow: none;
            color: #565656;
            height: 38px;
            max-width: 100%;
            padding: 7px 12px;
            -webkit-transition: all 300ms linear 0s;
            transition: all 300ms linear 0s;
        .select2-container
            width: 100% !important;
        .select2-container--open
            z-index: 9999 !important;

</style>